package com.schoolhelper.social.service.impl;

import com.schoolhelper.social.domain.Friendship;
import com.schoolhelper.social.dto.FriendRequestDTO;
import com.schoolhelper.social.dto.FriendDTO;
import com.schoolhelper.social.mapper.FriendshipMapper;
import com.schoolhelper.social.service.FriendshipService;
import com.schoolhelper.notification.service.NotificationService;
import com.schoolhelper.login.service.AuthService;
import com.schoolhelper.login.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

@Service
public class FriendshipServiceImpl implements FriendshipService {
    
    private static final Logger logger = LoggerFactory.getLogger(FriendshipServiceImpl.class);
    
    @Autowired
    private FriendshipMapper friendshipMapper;
    
    @Autowired
    private NotificationService notificationService;
    
    @Autowired
    private AuthService authService;
    
    @Override
    @Transactional
    public boolean sendFriendRequest(Long userId, Long friendId, String remark) {
        try {
            // 检查是否为自己
            if (userId.equals(friendId)) {
                logger.warn("用户不能添加自己为好友: userId={}", userId);
                return false;
            }
            
            // 检查是否已经存在好友关系或待处理的请求
            Friendship existingFriendship = friendshipMapper.findFriendship(userId, friendId);
            if (existingFriendship != null) {
                // 如果是已拒绝的请求，允许重新发送（更新为待确认状态）
                if (existingFriendship.getStatus() == Friendship.STATUS_REJECTED) {
                    logger.info("更新被拒绝的好友请求为待确认: userId={}, friendId={}", userId, friendId);
                    existingFriendship.setStatus(Friendship.STATUS_PENDING);
                    existingFriendship.setRemark(remark);
                    int result = friendshipMapper.updateFriendship(existingFriendship);
                    
                    if (result > 0) {
                        // 获取发送者信息
                        User sender = authService.getUserById(userId);
                        String senderName = (sender != null && sender.getUsername() != null) ? sender.getUsername() : "用户";
                        
                        // 创建新的好友请求通知
                        String title = "新的好友请求";
                        String content = senderName + " 向您发送了好友请求";
                        boolean notificationResult = notificationService.createFriendRequestNotification(
                            friendId, title, content, existingFriendship.getId(), userId);
                        
                        logger.info("重新发送好友请求成功: userId={}, friendId={}, notificationResult={}", 
                                   userId, friendId, notificationResult);
                        return true;
                    }
                    return false;
                } else {
                    // 其他状态（待确认、已同意）不允许重复发送
                    logger.warn("好友关系或请求已存在: userId={}, friendId={}, status={}", 
                               userId, friendId, existingFriendship.getStatus());
                    return false;
                }
            }
            
            // 检查反向关系
            Friendship reverseFriendship = friendshipMapper.findFriendship(friendId, userId);
            if (reverseFriendship != null) {
                // 如果反向关系是已拒绝的，也允许发送请求
                if (reverseFriendship.getStatus() != Friendship.STATUS_REJECTED) {
                    logger.warn("反向好友关系已存在: userId={}, friendId={}, status={}", 
                               userId, friendId, reverseFriendship.getStatus());
                    return false;
                }
            }
            
            // 创建新的好友请求
            Friendship friendship = new Friendship();
            friendship.setUserId(userId);
            friendship.setFriendId(friendId);
            friendship.setStatus(Friendship.STATUS_PENDING);
            friendship.setRemark(remark);
            
            int result = friendshipMapper.insertFriendship(friendship);
            
            if (result > 0) {
                // 获取发送者信息
                User sender = authService.getUserById(userId);
                String senderName = (sender != null && sender.getUsername() != null) ? sender.getUsername() : "用户";
                
                // 创建好友请求通知
                String title = "新的好友请求";
                String content = senderName + " 向您发送了好友请求";
                boolean notificationResult = notificationService.createFriendRequestNotification(
                    friendId, title, content, friendship.getId(), userId);
                
                logger.info("发送好友请求成功: userId={}, friendId={}, notificationResult={}", 
                           userId, friendId, notificationResult);
                return true;
            }
            
            return false;
            
        } catch (Exception e) {
            logger.error("发送好友请求失败: userId={}, friendId={}", userId, friendId, e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean handleFriendRequest(Long requestId, boolean accept) {
        try {
            int status = accept ? Friendship.STATUS_ACCEPTED : Friendship.STATUS_REJECTED;
            int result = friendshipMapper.updateFriendshipStatus(requestId, status);
            
            logger.info("处理好友请求: requestId={}, accept={}, result={}", requestId, accept, result);
            return result > 0;
            
        } catch (Exception e) {
            logger.error("处理好友请求失败: requestId={}, accept={}", requestId, accept, e);
            return false;
        }
    }
    
    @Override
    public List<FriendDTO> getUserFriends(Long userId) {
        try {
            logger.info("开始获取用户好友列表: userId={}", userId);
            List<FriendDTO> friends = friendshipMapper.findUserFriends(userId);
            logger.info("获取到的好友列表: userId={}, friendsCount={}", userId, friends != null ? friends.size() : 0);
            if (friends != null) {
                for (FriendDTO friend : friends) {
                    logger.info("好友信息: friendId={}, username={}, remark={}", friend.getFriendId(), friend.getUsername(), friend.getRemark());
                }
            }
            return friends;
        } catch (Exception e) {
            logger.error("获取用户好友列表失败: userId={}", userId, e);
            return null;
        }
    }
    
    @Override
    public List<FriendRequestDTO> getPendingRequests(Long userId) {
        try {
            return friendshipMapper.findPendingRequests(userId);
        } catch (Exception e) {
            logger.error("获取待确认好友请求失败: userId={}", userId, e);
            return null;
        }
    }
    
    @Override
    public List<Friendship> getSentRequests(Long userId) {
        try {
            return friendshipMapper.findSentRequests(userId);
        } catch (Exception e) {
            logger.error("获取发出的好友请求失败: userId={}", userId, e);
            return null;
        }
    }
    
    @Override
    @Transactional
    public boolean deleteFriend(Long userId, Long friendId) {
        try {
            // 首先检查是否为好友关系
            if (!friendshipMapper.isFriend(userId, friendId)) {
                logger.warn("尝试删除非好友关系: userId={}, friendId={}", userId, friendId);
                return false;
            }
            
            int result = friendshipMapper.deleteFriendship(userId, friendId);
            logger.info("删除好友关系: userId={}, friendId={}, result={}", userId, friendId, result);
            return result > 0;
        } catch (Exception e) {
            logger.error("删除好友关系失败: userId={}, friendId={}", userId, friendId, e);
            return false;
        }
    }
    
    @Override
    public boolean isFriend(Long userId, Long friendId) {
        try {
            return friendshipMapper.isFriend(userId, friendId);
        } catch (Exception e) {
            logger.error("检查好友关系失败: userId={}, friendId={}", userId, friendId, e);
            return false;
        }
    }
    
    @Override
    public boolean areFriends(Long userId1, Long userId2) {
        try {
            return friendshipMapper.isFriend(userId1, userId2);
        } catch (Exception e) {
            logger.error("检查好友关系失败: userId1={}, userId2={}", userId1, userId2, e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean updateFriendRemark(Long userId, Long friendId, String remark) {
        try {
            // 首先检查是否为好友关系
            if (!friendshipMapper.isFriend(userId, friendId)) {
                logger.warn("尝试更新非好友的备注: userId={}, friendId={}", userId, friendId);
                return false;
            }
            
            // 尝试更新现有记录
            int result = friendshipMapper.updateFriendRemark(userId, friendId, remark);
            
            // 如果没有更新到记录，说明当前用户没有对应的记录，需要创建
            if (result == 0) {
                result = friendshipMapper.insertOrUpdateFriendRemark(userId, friendId, remark);
            }
            
            logger.info("更新好友备注: userId={}, friendId={}, remark={}, result={}", userId, friendId, remark, result);
            return result > 0;
        } catch (Exception e) {
            logger.error("更新好友备注失败: userId={}, friendId={}", userId, friendId, e);
            return false;
        }
    }
}